<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .canvas{
            border: 1px solid red;
        }
    </style>
</head>
<body>
<canvas class="canvas" width="600px" height="400px">
    您的浏览器不支持
</canvas>
<script>
    var canvas = document.getElementsByClassName('canvas')[0]
    var ctx = canvas.getContext('2d')

    var str = 'hello world'
    //设置文本样式，比如大小，字体
    ctx.font = '50px sans-serif'
    //水平对齐设置，left center right
    ctx.textAlign = 'center'
    //垂直对齐设置， top middle bottom
    ctx.textBaseline = 'bottom'
    //填充文本
    ctx.fillText(str,300,100)
    //描边文本
    ctx.strokeText(str,300,300)
    //获取文本宽度
    var textWidth = ctx.measureText(str).width
    console.log(textWidth)

</script>
</body>
</html>
